from django.shortcuts import render
from django.views import View
from django.http import JsonResponse,HttpResponse,request
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from rest_framework.views import APIView,exceptions
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from rest_framework.parsers import JSONParser,FormParser
from rest_framework import serializers
import hashlib,time,json
from aaa import models

def md5(user):
    m = hashlib.md5(user.encode('utf-8'))
    ctime = str(time.time())
    m.update(ctime.encode('utf-8'))
    return m.hexdigest()

visit_record = {}
class visitedThrottle(APIView):
    '''60s内只能访问3次'''

    def __init__(self):
        self.history = None

    def allow_request(self,request,view):
        remote_addr = request.META.get('REMOTE_ADDR')
        ctime = time.time()
        #第一次访问写入记录返回True
        if 'remote_addr' not in visit_record:
            visit_record['remote_addr'] = [ctime,]
            print(visit_record)
            return True
        history = visit_record.get('remote_addr')
        self.history = history
        while history and history[-1] < ctime - 60:
            history.pop()
        if len(history) < 3:
            history.insert(0,ctime)
            print('--> history', history)
            return True

    def wait(self):
        ctime = time.time()
        return 60 - (ctime - self.history[-1])

class authView(APIView):
    '''用于用户认证'''

    authentication_classes = []
    permission_classes = []
    # throttle_classes = [visitedThrottle,]
    def post(self,request,*args,**kwargs):
        ret = {'meta':{'status':200,'msg':None}}
        try:
            user = request._request.POST.get('username')
            pwd = request._request.POST.get('password')
            print(pwd)
            obj = models.userInfo.objects.filter(username=user,password=pwd).first()
            print('obj',obj)
            if not obj:
                ret['meta']['status'] = 201
                ret['meta']['msg'] = '用户或密码错误'
                # raise exceptions.AuthenticationFailed('用户或密码错误')
            token = md5(user)
            print(token)
            models.userToken.objects.update_or_create(user=obj,defaults={'token':token})
            ret['data'] = {'token':token}
            print(ret)
        except Exception as e:
            ret['meta']['status'] = 201
            ret['meta']['msg'] = e
        return JsonResponse(ret)

order_dict = {
    1:{
        'name':'tom',
        'age':'one'
    },
    2: {
        'name': 'wangwang',
        'age': 'two'
    }
}
class orderView(APIView):
    '''订单相关业务'''
    def get(self,request,*args,**kwargs):
        try:
            ret = {'meta': {'status': 200, 'msg': None}}
            # if request.user.user_type != 0:
            #     ret['meta']['msg'] = '无权访问'
            #     ret['meta']['status'] = 201
            #     return JsonResponse(ret)
            ret['data'] = order_dict

        except Exception as e:
            pass
        return JsonResponse(ret)

# class userInfoSerializer(serializers.Serializer):
#     xxx = serializers.CharField(source='get_user_type_display')
#     username = serializers.CharField()
#     password = serializers.CharField()
#     gp = serializers.CharField(source='group.title')
#     rls = serializers.SerializerMethodField()
#     def get_rls(self,row):
#         role_obj_list = row.roles.all()
#         ret = []
#         for item in role_obj_list:
#             ret.append({'id':item.id,'title':item.title})
#         return ret

class userInfoSerializer(serializers.ModelSerializer):
    group = serializers.HyperlinkedIdentityField(view_name='gp',lookup_field='group_id',lookup_url_kwarg='pk')
    class Meta:
        model = models.UserInfo
        fields =  ['id','username','group']

class userGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserGroup
        fields = '__all__'

from rest_framework.viewsets import GenericViewSet,ModelViewSet
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination
from aaa.utils.pager import PagerSerialiser

class MyLimitOffsetPagination(GenericViewSet):
    default_limit = 2
    limit_query_param = 'limit'
    offset_query_param = 'offset'
    max_limit = None

class userInfoView(ModelViewSet):
    queryset = models.UserInfo.objects.all()
    serializer_class = PagerSerialiser
    pagination_class = PageNumberPagination

    # def get(self, request, *args, **kwargs):
    #     # 获取数据
    #     roles = models.UserInfo.objects.all()
    #     pg = PageNumberPagination()
    #
    #     # 在数据库中获取分页的数据
    #     xx = pg.paginate_queryset(queryset=roles,request=request,view=self)
    #     print('xx',xx)
    #     # 对数据进行序列化
    #     ser = PagerSerialiser(instance=xx, many=True)
    #     print(ser)
    #     return Response(ser.data)
    #     # return pg.get_paginated_response(ser.data)

    def post(self,request,*args,**kwargs):
        print(request.data)
        return HttpResponse('gee')

class userGroupView(APIView):
    def get(self,request,*args,**kwargs):
        pk = kwargs.get('pk')
        group = models.UserGroup.objects.filter(pk=pk).first()
        ser = userGroupSerializer(instance=group,many=False)
        ret = json.dumps(ser.data,ensure_ascii=False)
        return HttpResponse(ret)

class roleSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    ttt = serializers.CharField(source='title')

class rolesView(APIView):
    '''订单相关业务'''
    authentication_classes = []
    permission_classes = []
    def get(self,request,*args,**kwargs):
        roles = models.Role.objects.all().first()
        ser = roleSerializer(instance=roles,many=False)
        ret = json.dumps(ser.data,ensure_ascii=False)
        return HttpResponse(ret)

    def post(self,request,*args,**kwargs):
        pass